package com.example.demo.service;


import com.example.demo.mapper.TeacherMapper;

import com.example.demo.model.Teacher;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import java.util.List;


@Service

public class TeacherService {


    @Autowired

    private TeacherMapper teacherMapper;


    public List<Teacher> list() {

        return teacherMapper.findAll();

    }


    public void delete(Integer id) {

        teacherMapper.delete(id);

    }


    public void save(Teacher s) throws Exception {

        if (teacherMapper.findByTel(s.getTel()).size() > 0) {

            throw new Exception("Tel already exists when save");

        }

        teacherMapper.save(s);

    }


    public Teacher get(Integer id) {

        return teacherMapper.get(id);

    }


    public void update(Teacher s) throws Exception {

        List<Teacher> teachers = teacherMapper.findByTel(s.getTel());

        if (teachers.size() > 1) {

            throw new Exception("Tel already exists when update");

        } else if (teachers.size() == 1) {

            if (!teachers.get(0).getId().equals(s.getId())) {

                throw new Exception("Tel already exists when update");

            }

        }

        teacherMapper.update(s);

    }


    public List<Teacher> search(Teacher teacher) {

        return teacherMapper.search(teacher);

    }

}